#include "licensedialog.h"
#include "licensemanager.h"
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QFormLayout>
#include <QMessageBox>
#include <QDesktopServices>
#include <QUrl>

LicenseDialog::LicenseDialog(QWidget *parent)
    : QDialog(parent)
{
    setupUI();
    createConnections();
    updateLicenseInfo();
}

void LicenseDialog::setupUI()
{
    setWindowTitle(tr("授权信息"));
    setMinimumWidth(400);

    QVBoxLayout* mainLayout = new QVBoxLayout(this);
    
    // 状态信息
    m_statusLabel = new QLabel(this);
    m_statusLabel->setWordWrap(true);
    mainLayout->addWidget(m_statusLabel);
    
    // 硬件ID
    QFormLayout* formLayout = new QFormLayout;
    m_hardwareIdLabel = new QLabel(this);
    m_hardwareIdLabel->setTextInteractionFlags(Qt::TextSelectableByMouse);
    formLayout->addRow(tr("硬件ID:"), m_hardwareIdLabel);
    
    // 授权码输入
    m_licenseKeyEdit = new QLineEdit(this);
    formLayout->addRow(tr("授权码:"), m_licenseKeyEdit);
    mainLayout->addLayout(formLayout);
    
    // 按钮
    QHBoxLayout* buttonLayout = new QHBoxLayout;
    m_activateButton = new QPushButton(tr("激活"), this);
    m_purchaseButton = new QPushButton(tr("购买授权"), this);
    m_closeButton = new QPushButton(tr("关闭"), this);
    
    buttonLayout->addWidget(m_purchaseButton);
    buttonLayout->addStretch();
    buttonLayout->addWidget(m_activateButton);
    buttonLayout->addWidget(m_closeButton);
    
    mainLayout->addLayout(buttonLayout);
}

void LicenseDialog::createConnections()
{
    connect(m_activateButton, &QPushButton::clicked, this, &LicenseDialog::activateLicense);
    connect(m_purchaseButton, &QPushButton::clicked, this, &LicenseDialog::purchaseLicense);
    connect(m_closeButton, &QPushButton::clicked, this, &QDialog::accept);
}

void LicenseDialog::updateLicenseInfo()
{
    auto& manager = LicenseManager::instance();
    
    if (manager.isLicensed()) {
        m_statusLabel->setText(tr("当前状态: 已授权\n授权类型: 专业版\n到期时间: 永久"));
        m_licenseKeyEdit->setEnabled(false);
        m_activateButton->setEnabled(false);
    } else {
        m_statusLabel->setText(tr("当前状态: 未授权\n您正在使用试用版，导出的文件将包含水印。"));
        m_licenseKeyEdit->setEnabled(true);
        m_activateButton->setEnabled(true);
    }
    
    m_hardwareIdLabel->setText(manager.getHardwareId());
}

void LicenseDialog::activateLicense()
{
    QString licenseKey = m_licenseKeyEdit->text().trimmed();
    if (licenseKey.isEmpty()) {
        QMessageBox::warning(this, tr("错误"), tr("请输入授权码"));
        return;
    }
    
    if (LicenseManager::instance().activateLicense(licenseKey)) {
        QMessageBox::information(this, tr("成功"), tr("授权激活成功！"));
        updateLicenseInfo();
    } else {
        QMessageBox::warning(this, tr("错误"), tr("授权码无效或已被使用"));
    }
}

void LicenseDialog::purchaseLicense()
{
    QDesktopServices::openUrl(QUrl("https://your-website.com/purchase"));
} 